/**
 * @author 李鑫，弘治
 * 加下拉箭头
 * 缓存全国
 * 异地编码的时候将城市载入
 * 
 * 
 * searchPlace的时候提供一个"全国/北京"这样的一个路径
 */
var REGO = {};
var regionCode,rgeoPoint=null,rgeoPrecision=2000,rgeoTime=1000,rgeoTimeout;
//逆地理编码地址
var rgeoUrl="http://rgc.51ditu.com/rgeo?rt=js&ll=";	

//这个函数在localSearch.js里面被调用,页面onload时候,即页面加载完成的时候，就会进行寻找中心点的行政区划
function initRego(){
	//获取到地图的中心点
	var centerPoint = map.getCenterPoint();
	//调用函数获取中心点的行政区划
	getRgeoCode(centerPoint);
	//给地图的移动添加事件，注意，这里getRgeoCode是没有带有参数的，这个问题将会在getRgeoCode中加以处理
	LTEvent.addListener(map,"move",getRgeoCode);
}
/**
 * 根据中心点获取到行政区划的编码 
 * @param {Object} point 地图中心点
 */
function getRgeoCode(point)
{
	if(!point)
	{
		//如果传入的point不是空值或者undefined，但是发送过去的经纬度是从rgeoPoint中取得，这个是我没有想通
		if(!REGO.rgeoLoader){   
		    //FIXME 对于这个类的描述，我没有找到，说明这个是一个没有公开的类 
			REGO.rgeoLoader=new LTObjectLoader();
			//清空和添加事件 
			LTEvent.clearListeners(REGO.rgeoLoader);
			LTEvent.addListener(REGO.rgeoLoader,"loaded",onRgeoCode);
		}
		//发出ajax的请求
		REGO.rgeoLoader.load(rgeoUrl+rgeoPoint[0]+","+rgeoPoint[1],"GB2312");
	}else{
		//需要问一下李鑫这个公式是做什么的
		rgeoPoint=[parseInt(point.getLongitude()/rgeoPrecision)*rgeoPrecision+rgeoPrecision/2,parseInt(point.getLatitude()/rgeoPrecision)*rgeoPrecision+rgeoPrecision/2];
		//？？
		if(rgeoTimeout){window.clearTimeout(rgeoTimeout);}
		//在地图移动停止一秒后才去获取编码
		//疑惑之处，
		rgeoTimeout=window.setTimeout(getRgeoCode,rgeoTime);
	}
}
/**
 *在接收到逆地理编码请求时处理 
 * @param {Object} obj  一个json的对象，当中包含着行政区划的信息
 */
function onRgeoCode(obj)
{
    //如果是设置城市引起的地图move,择不设置逆地理编码
	if(CityLink.versionOld!=CityLink.versionNew){
		CityLink.versionOld = CityLink.versionNew;
		return;
	}
	var area = obj.c[1].t;
	var areas = area.split("-");
    //显示逆地理编码的城市
	CityLink.getInstance().reset(areas,"regoSpan");
	//？
	if(obj.c[1].a.regionCode!=regionCode)
	{
		regionCode=obj.c[1].a.regionCode;
	}
}


//	点击body隐藏弹出菜单
LTEvent.addListener(window,"load",
                      function(obj){ 
					        LTEvent.addListener(document.body,"click",CityLink.hiddendisplay,false);
				      },false);


function CityLink(){
	//	缓存全国(怪异问题)，这个注释是李鑫加入的，我没有看懂
	if(CityLink.countryDiv){
		document.body.appendChild(CityLink.countryDiv);
		CityLink.countryDiv.parentNode.removeChild(CityLink.countryDiv);
	}
//	CityLink.countryDiv = null;
	CityLink.countryDiv = document.createElement("div");
	var ltPlaces = CityLink.placeList.searchPlace("全国")[0];
	var	placesChild = ltPlaces.getChildren();
	for(var k=0;k<placesChild.length;k++){
		var area = document.createElement("div");
		CityLink.countryDiv.appendChild(area);
		area.className = "CityLinkArea";
		area.setAttribute("class","CityLinkArea");
		area.innerHTML = placesChild[k].getName();
		this.appendCity(CityLink.countryDiv,placesChild[k].getName(),0);
	}
}
CityLink.newInstance = null;
CityLink.getInstance = function(){
	if(CityLink.newInstance==null){
		CityLink.newInstance = new CityLink();
	}
	return CityLink.newInstance;
}
CityLink.prototype.reset = function(args,spanId){
	this.span = document.getElementById(spanId);
	this.span.className = "b01";
	this.span.setAttribute("class","b01");
//	删除节点
	while(this.span.firstChild){
		LTEvent.clearListeners(this.span.firstChild);
		this.span.firstChild.parentNode.removeChild(this.span.firstChild);
	}
	if(CityLink.displayDiv==null){
		CityLink.displayDiv = document.createElement("div");
		CityLink.displayDiv.style.position = "absolute";
		CityLink.displayDiv.style.display = "none";
	}
//	删除过,所以要再加上
	this.span.appendChild(CityLink.displayDiv);	
//	全国
	this.country =  document.createElement("a");
	this.country.innerHTML = "全国" + CityLink.listImg;
	this.span.appendChild(this.country);
	LTEvent.bind(this.country,"click",this,this.show(0));
	this.country.onmouseover = this.mouseover;
//	省,市,区
	this.ary = [this.country];
//	由省市对应到place里面去
	this.aryToPlace = [];
	var obj = this;
//	要装载数据的place
	this.loadPlaces = [];
	for(var i=0;i<args.length;i++){
		this.ary[i+1] = document.createElement("a");
//		this.ary[i+1].name = args[i];
		this.span.appendChild(this.ary[i+1]);
//		有下级城市才可以搜索
		var ltPlaces = CityLink.placeList.searchPlace(args[i]);
		
//		区分城市是否重复
//		地名重复并且是生成省的时候
		if(ltPlaces.length>1&&i==0){
			for(var j=0;j<ltPlaces.length;j++){
				if(ltPlaces[j].hasChildren()){
					ltPlaces = [ltPlaces[j]];
				}
			}
		}
		
//		加载place
		if(ltPlaces.length>0&&ltPlaces[0].hasChildren()&&ltPlaces[0].getChildren().length<1){
			this.loadPlaces.push(ltPlaces[0]);
//			设置省市对应的place
			this.aryToPlace[i+1] = this.loadPlaces[this.loadPlaces.length-1];
		}else if(ltPlaces.length>0&&ltPlaces[0].hasChildren()&&ltPlaces[0].getChildren().length>0){
			this.aryToPlace[i+1] = ltPlaces[0];
		}
//		加载事件
		if(ltPlaces.length>0&&ltPlaces[0].hasChildren()){
			LTEvent.bind(this.ary[i+1],"click",this,this.show(i+1));
			LTEvent.bind(this.ary[i+1],"mouseover",this.ary[i+1],this.mouseover);
		}else{
			LTEvent.bind(this.ary[i+1],"click",this,this.hiddenDisplayDiv);
		}
//		设置图片
		if(ltPlaces.length>0&&ltPlaces[0].hasChildren()){
			this.ary[i+1].innerHTML = args[i] + CityLink.listImg;
		}else{
			this.ary[i+1].innerHTML = args[i];
		}
//		this.ary[i+1].onmouseover = this.mouseover;
	}
//	加载城市
//debug
//	this.loadPlaces = [CityLink.placeList.searchPlace("山西")[0],CityLink.placeList.searchPlace("朔州")[0]];
//	this.loadPlaces = [CityLink.placeList.searchPlace("朔州")[0]];
	LTGetChildPlace.getInstance().loadPlacesData(this.loadPlaces);
	

	

}
//用传入的i来判断是省,市,或者是区
//如果没有结果择不显示
CityLink.prototype.show = function(i){
	return function(){
		if(CityLink.displayDiv.style.display == "none"){
//			var city = this.ary[i].name;
//			替换两个--
//			var city = this.ary[i].firstChild.data.replace(/--/g,"");
			var city = this.ary[i].firstChild.data;
//			删除所有节点
			if(CityLink.lastCity=="全国"&&CityLink.displayDiv.firstChild){
				CityLink.countryDiv = CityLink.displayDiv.firstChild.parentNode.removeChild(CityLink.displayDiv.firstChild);
			}else{
				while(CityLink.displayDiv.firstChild){
					CityLink.displayDiv.firstChild.parentNode.removeChild(CityLink.displayDiv.firstChild);
				}
			}
			
//			显示城市的下属城市
			if(city=="全国"){
				CityLink.displayDiv.appendChild(CityLink.countryDiv);
				
			}else{
	//			把city下面的城市全部放到弹出div里面
				this.appendCityByPlace(CityLink.displayDiv,this.aryToPlace[i],i);
			}
//			CityLink.displayDiv.innerHTML = "<span>显示各个城市</span>";
			var pos = LTFunction.getPageOffset(this.ary[i]);
			CityLink.displayDiv.style.left = pos[0] + this.ary[i].offsetWidth;
			CityLink.displayDiv.style.top = pos[1] + this.ary[i].offsetHeight;
//			CityLink.displayDiv.style.left = pos[0] ;
//			CityLink.displayDiv.style.top = pos[1];
			CityLink.displayDiv.className = "CityLink";
			CityLink.displayDiv.setAttribute("class","CityLink");
			CityLink.displayDiv.style.display = "inline";
			CityLink.displayDiv.scrollTop = 0;
//			用这个i来判断上次显示在哪个等级上面了
			CityLink.displayDiv.i = i;
		}else{
//			如果不在上次的等级上面
			if(CityLink.displayDiv.i==i){
				CityLink.displayDiv.style.display = "none";
			}else{
				CityLink.displayDiv.style.display = "none";
//				再调用一次,显示出城市
				var obj = this;
				this.show(i).call(obj);
			}
			
		}
//		保存当前被点击的省或者国
		CityLink.lastCity = city;
//		no firefox
		Event.stop(window.event);
	}
}
//当前上下文为当前的元素对象
CityLink.prototype.mouseover = function(){
	this.style.cursor = "hand";
}
//点击城市的时候设置值
CityLink.prototype.setCity = function(ele,i){
	return function(){
//		删除所有兄弟节点,将值设入
		while(this.ary[i].nextSibling){
			this.ary[i].nextSibling.parentNode.removeChild(this.ary[i].nextSibling);
		}
//		取当前节点的父路径
//		var cityPath = this.getAllPath(this.ary[i],i,ele);
//		alert(this.getAllPath(this.ary[i],i,ele));

		this.ary[i+1] = document.createElement("a");
//		var ltPlaces = CityLink.placeList.searchPlace(cityPath);
		
		var ltPlaces = CityLink.placeList.searchPlace(ele.firstChild.data);
//		地名重复并且是点击全国的时候
		if(ltPlaces.length>1&&i==0){
			for(var j=0;j<ltPlaces.length;j++){
				if(ltPlaces[j].hasChildren()){
					ltPlaces = [ltPlaces[j]];
				}
			}
		}
//		([ele.firstChild.data,ltPlaces.length])
		if(ltPlaces.length>0&&ltPlaces[0].hasChildren()){
			this.ary[i+1].innerHTML = ele.firstChild.data + CityLink.listImg;
	//		添加事件
			LTEvent.bind(this.ary[i+1],"click",this,this.show(i+1));
			LTEvent.bind(this.ary[i+1],"mouseover",this.ary[i+1],this.mouseover);
//			设置省市对应的place
			this.aryToPlace[i+1] = ltPlaces[0];
//			如果有子节点并且子节点为0则加载子节点
			if(ltPlaces[0].getChildren().length==0){
				LTGetChildPlace.getInstance().loadPlacesData([ltPlaces[0]]);
			}
			
		}else{
			this.ary[i+1].innerHTML = ele.firstChild.data;
		}
//		this.ary[i+1].name = ele.firstChild.data;
		this.ary[i].parentNode.appendChild(this.ary[i+1]);		
		
		CityLink.displayDiv.style.display = "none";
//		(ele,i);
//		移动地图
		//获取该地名的坐标
		if(ltPlaces.length>0){
			var point=ltPlaces[0].getPoint();
			if(point)
			{//有些地名可能没有坐标信息
				map.centerAndZoom(point,CityLink.mapZoom[i]);
			}
		}
		
		CityLink.versionNew++;		

	}
}
//此函数无用
//传入名字和级别(省或者市)
//拖动结束的时候是获得不了区的,所以只能从上到下取区
CityLink.prototype.getAllPath = function(city,i,ele){
	//		取当前节点的父路径
	var preEle = city;
	var cityPath = "";
//	var ltPlaces = CityLink.placeList.searchPlace("全国")[0];
//	var	placesChild = ltPlaces.getChildren();
//	for(var r=0;r<placesChild.length;r++){
//		("55"+placesChild[r].getName());
//	}
//		从全国中取华北等区
	var countplace = CityLink.placeList.searchPlace("全国")[0];
	while(preEle){
		if(preEle.tagName.toLowerCase()=="a"){
			if(cityPath==""){
				cityPath = (preEle.firstChild.data);
			}else{
				cityPath = (preEle.firstChild.data) + "-" + cityPath;
			}
			document.title = cityPath;
		}
		preEle = preEle.previousSibling;
	}
	return cityPath  + "-" + ele.firstChild.data;
}

CityLink.prototype.appendCity = function(parent,city,i){
	var ltPlaces = CityLink.placeList.searchPlace(city,0)[0];
	this.appendCityByPlace(parent,ltPlaces,i);
}
CityLink.prototype.appendCityByPlace = function(parent,place,i){
	var ltPlaces = place;
	var placeChild = place.getChildren();
	for(var j = 0;j<placeChild.length;j++){
		var cityN = document.createElement("div");
		parent.appendChild(cityN);
		cityN.innerHTML = placeChild[j].getName();
		cityN.className = "CityLinkChild";
		cityN.setAttribute("class","CityLinkChild");
//		i:等级,点击的时侯设置到下一级里面
		LTEvent.bind(cityN,"click",this,this.setCity(cityN,i));
		LTEvent.bind(cityN,"mouseover",cityN,this.mouseover);
	}
}
CityLink.prototype.hiddenDisplayDiv = function(){
	if(CityLink.displayDiv.style){
		CityLink.displayDiv.style.display = "none";
	}
}
CityLink.hiddendisplay = function(){
	if(CityLink.displayDiv){
		CityLink.displayDiv.style.display = "none";
	}
}
//
CityLink.displayDiv = null;
CityLink.placeList = LTPlaceList.getDefault();
CityLink.countryDiv = null;
CityLink.mapZoom = [6,4,2,1];
//保存上次被点击的省或国
CityLink.lastCity = "";
//
CityLink.versionOld = 1;
CityLink.versionNew = 1;
CityLink.listImg = '<IMG class="img01" src="comm/img/list2.png" />';


function LTGetChildPlace(){
	this.loadUrl = "http://api.51ditu.com/place/china/";
}
LTGetChildPlace.newInstance = null;
LTGetChildPlace.completeNum = 0;
LTGetChildPlace.getInstance = function(){
	if(LTGetChildPlace.newInstance==null){
		LTGetChildPlace.newInstance = new LTGetChildPlace();
	}
//	完成装载城市数起始为0
	LTGetChildPlace.completeNum = 0;
	return LTGetChildPlace.newInstance;
//	return new LTGetChildPlace();
}
//LTGetChildPlace._LT_pld_url = "http://api.51ditu.com/place/china/";
LTGetChildPlace.prototype.onPlaceLoaded=function(place)
{
	//p.js
	return function(obj)
	{
		
		place.loadChildren(obj);
		++LTGetChildPlace.completeNum;
//		(place.getName());
//		([place.getName(),place.getChildren()[0].getName(),place.getChildren()[1].getName()]);
//		var restest = LTPlaceList.getDefault().searchPlace(place.getName(),0)[0];
//		([restest.getName(),restest.getChildren()[0].getName(),restest.getChildren()[1].getName()]);
		
		
		this.loadPlacesData(this.plaAry);
		
	}
}
LTGetChildPlace.prototype.loadPlaceData=function(place)
{
	var loader=LTObjectLoader.getObject();
	LTEvent.bind(loader,"loaded",this,this.onPlaceLoaded(place),true);
	loader.load(this.getLoadUrl(place));
}
LTGetChildPlace.prototype.getLoadPath=function(place)
{
	if(!place.parent){return this.loadUrl;}
//	(place.getName() + ":path")
	return this.getLoadPath(place.parent)+encodeURI(place.getName()).replace(new RegExp("%","g"),"")+"/";
}
LTGetChildPlace.prototype.getLoadUrl=function(place)
{
	return this.getLoadPath(place)+"p.js";
}
LTGetChildPlace.prototype.loadPlacesData = function(plaAry){
//	处理完毕则返回
	this.plaAry = plaAry;
	if(LTGetChildPlace.completeNum == (plaAry.length)){
		return;
	}
	this.loadPlaceData(plaAry[LTGetChildPlace.completeNum]);
	
}